package com.sos.service.impl;

import com.sos.exception.CustomException;
import com.sos.exception.ErrorCode;
import com.sos.model.vo.ResultVO;
import com.sos.service.FileUploadService;
import com.sos.util.UserContextUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.UUID;

@Service
@RequiredArgsConstructor
@Slf4j
public class FileUploadServiceImpl implements FileUploadService {

    private final UserContextUtils userContextUtils;

    @Value("${file.upload.path}")
    private String uploadPath;

    @Value("${file.access.path}")
    private String accessPath;

    @Override
    public ResultVO<String> uploadAvatar(MultipartFile file) {
        // 检查文件是否为空
        if (file.isEmpty()) {
            throw new CustomException(ErrorCode.FILE_UPLOAD_ERROR, "上传文件不能为空");
        }

        // 检查文件类型
        if (!isImageFile(file)) {
            throw new CustomException(ErrorCode.FILE_UPLOAD_ERROR, "只允许上传图片文件(jpg, jpeg, png, gif)");
        }

        // 检查文件大小（限制为5MB）
        if (file.getSize() > 5 * 1024 * 1024) {
            throw new CustomException(ErrorCode.FILE_UPLOAD_ERROR, "文件大小不能超过5MB");
        }

        try {
            // 生成唯一文件名
            String originalFilename = file.getOriginalFilename();
            String fileExtension = getFileExtension(originalFilename);
            String uniqueFilename = UUID.randomUUID().toString() + "." + fileExtension;

            // 创建年月日目录结构
            String datePath = java.time.LocalDate.now().toString().replace("-", "/");
            Path uploadDir = Paths.get(uploadPath, "avatars", datePath);
            Files.createDirectories(uploadDir);

            // 保存文件
            Path filePath = uploadDir.resolve(uniqueFilename);
            Files.copy(file.getInputStream(), filePath, StandardCopyOption.REPLACE_EXISTING);

            // 构造访问URL (使用固定的API路径，避免双斜杠问题)
            String fileUrl = "/api" + accessPath + "/avatars/" + datePath + "/" + uniqueFilename;
            
            // 去掉开头的"/"符号
            String frontendUrl = fileUrl.startsWith("/") ? fileUrl.substring(1) : fileUrl;

            log.info("用户头像上传成功，文件路径：{}", fileUrl);
            return ResultVO.success(frontendUrl);
        } catch (IOException e) {
            log.error("文件上传失败", e);
            throw new CustomException(ErrorCode.FILE_UPLOAD_ERROR, "文件上传失败：" + e.getMessage());
        }
    }

    /**
     * 检查文件是否为图片类型
     */
    private boolean isImageFile(MultipartFile file) {
        try {
            BufferedImage image = ImageIO.read(file.getInputStream());
            // 检查文件扩展名
            String filename = file.getOriginalFilename().toLowerCase();
            return image != null && 
                   (filename.endsWith(".jpg") || filename.endsWith(".jpeg") || 
                    filename.endsWith(".png") || filename.endsWith(".gif"));
        } catch (IOException e) {
            return false;
        }
    }

    /**
     * 获取文件扩展名
     */
    private String getFileExtension(String filename) {
        if (filename == null || filename.lastIndexOf(".") == -1) {
            return "";
        }
        return filename.substring(filename.lastIndexOf(".") + 1);
    }
}